const Route = require('../../enhance/route').Route
const Stores = require('../../enhance/stores').Stores
const MemStores = require('../../enhance/mem-stores').MemStores

Page({
    data: {
        HOST: 'http://192.168.1.7:3000',
        navbar: ['盘点项', '跳过项', '存档记录'],
        tab: 0,
        items: []
    },

    onLoad(options) {
        MemStores.set('toto-items', Stores.get('todo-items') || [])
    },

    onUnload() {
        Stores.set('todo-items', MemStores.get('todo-items'))
    },

    onShow() {
        let items = MemStores.get('todo-items')
        this.setData({ items })
    },

    navbarTap(e) {
        let tab = e.currentTarget.dataset.idx
        this.setData({ tab })
    },

    snap(e) {

        let self = this

        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['camera'],
            success: res => {
                const filePath = res.tempFilePaths[0]
                Route.to('item-detail', { type: 'snap', filePath })
            }
        })
    },

    scan(e) {

        let self = this

        wx.scanCode({
            onlyFromCamera: true,
            scanType: ['barCode'],
            success: res => {
                console.log(res)
                let barcode = res.result
                if (barcode.length != 13) {
                    wx.showToast({ icon: 'none', title: '请对照商品条形码进行扫描！' })
                    setTimeout(() => { self.scan({}) }, 0);
                }
                else {
                    Route.to('item-detail', { type: 'scan', barcode })
                }
            }
        })
    },

    detail(e) {

        let { index } = e.currentTarget.dataset
        let { items } = this.data

        Route.to('item-detail', Object.assign({ editIndex: index }, items[index]))
    },

    skip(e) {

        let { index } = e.currentTarget.dataset
        let { items } = this.data

        items[index].skiped = true;
        
        this.setData({ items })
        MemStores.set('todo-items', items)
    },

    archive(e) {

        let { index } = e.currentTarget.dataset
        let { items } = this.data

        items[index].archived = true;
        
        this.setData({ items })
        MemStores.set('todo-items', items)
    }
})
